<?php

namespace app\models;

use Yii;
use yii\base\Model;

/**
 * ContactForm is the model behind the contact form.
 */
class ContactForm extends Model
{
    public $name;
    public $username;
    public $password;
    public $email;
    public $subject;
    public $body;
    public $verifyCode;

    private $_user = null;
    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [

            [['name', 'email', 'subject', 'body','username','password'], 'required'],

            ['email', 'email'],

            ['verifyCode', 'captcha'],

            ['username','validateUsername'],
        ];
    }
    //验证用户是否存在
    public function validateUsername($attribute, $params)
    {
        if (!$this->hasErrors()) {
            if ($this->getUser()) {
                $this->addError($attribute, 'Another User has this username');
            }
        }
    }
    /**
     * @return array customized attribute labels
     */
    public function attributeLabels()
    {
        return [
            'verifyCode' => 'Verification Code',
        ];
    }

    /**
     * Sends an email to the specified email address using the information collected by this model.
     * @param string $email the target email address
     * @return bool whether the model passes validation
     */
    public function contact($email)
    {
        if ($this->validate()) {
            Yii::$app->mailer->compose()
                ->setTo($email)
                ->setFrom([$this->email => $this->name])
                ->setSubject($this->subject)
                ->setTextBody($this->body)
                ->send();
            return true;
        }
        return false;
    }

    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
    public function getUser()
    {
        if ($this->_user === false) {
            $this->_user = User::findByUsername($this->username);
        }

        return $this->_user;
    }
}
